package com.mytomcat.catalina.pipeline;

import com.mytomcat.catalina.container.Container;
import com.mytomcat.catalina.valve.Valve;
import java.util.ArrayList;
import java.util.List;

/**
 * 标准管道
 *
 * @author supu
 * @date 2019-04-19 13:54
 **/
public class StandardPipeline implements Pipeline {
    protected Valve basic;

    protected Valve first;

    protected Container container;

    public StandardPipeline() {
        this(null);
    }

    public StandardPipeline(Container container) {
        this.container = container;
    }

    @Override
    public void setBasic(Valve valve) {
        this.basic = valve;
    }

    @Override
    public Valve getBasic() {
        return basic;
    }

    @Override
    public void addValve(Valve valve) {
        if (first == null) {
            first = valve;
            valve.setNext(basic);
        } else {
            Valve current = this.first;
            while (current != null) {
                if (current.getNext() == basic) {
                    // 找到了basic节点之后，将valve插入到basic之前的节点
                    current.setNext(valve);
                    valve.setNext(basic);
                    break;
                }
                current = current.getNext();
            }
        }
    }

    @Override
    public List<Valve> getValves() {
        List<Valve> valves = new ArrayList<>();
        Valve current = getFirst();
        while (current != null) {
            valves.add(current);
            if (current == basic) {
                break;
            }
            current = current.getNext();
        }
        return valves;
    }

    @Override
    public Valve getFirst() {
        if (first == null) {
            return basic;
        }
        return first;
    }

    @Override
    public void removeValve() {

    }
}
